<?php

namespace App\Service;

use App\Constants\ErrorCode;
use App\Context\UserInfoContext;
use App\Model\AdminAuthGroup;
use App\Model\AdminAuthGroupAccess;
use App\Model\AdminAuthRule;
use Hyperf\Context\Context;
use RuntimeException;

class AdminPermissionService {

    public function __construct($router) {
        $userInfoContext = Context::get(UserInfoContext::class);
        if (!$this->checkAuth($userInfoContext->userInfo['id'], $router)) {
            throw new RuntimeException('非常抱歉，您没有权限这么做！', ErrorCode::INVALID);
        }
    }

    /**
     * 检测用户权限
     * @param $uid
     * @param $route
     * @return bool
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    private function checkAuth($uid, $route): bool {
        $isSupper = ToolService::isAdministrator($uid);
        if (!$isSupper) {
            $rules = $this->getAuth($uid);

            return in_array($route, $rules);
        }

        return true;
    }

    /**
     * 根据用户ID获取全部权限节点
     * @param $uid
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    private function getAuth($uid): array {
        $groups = AdminAuthGroupAccess::query()->where('uid', $uid)->first();
        if (isset($groups) && $groups->getAttribute('group_id')) {
            $openGroup = AdminAuthGroup::query()->whereIn('id', explode(',', $groups->getAttribute('group_id')))
                ->where('status', 1)->get();
            if (isset($openGroup)) {
                $openGroupArr = [];
                foreach ($openGroup as $group) {
                    $openGroupArr[] = $group->id;
                }
                $allRules = AdminAuthRule::query()->whereIn('group_id', $openGroupArr)->get();
                if (isset($allRules)) {
                    $rules = [];
                    foreach ($allRules as $rule) {
                        $rules[] = $rule->url;
                    }

                    return array_unique($rules);
                }
            }
        }

        return [];
    }

}